package com.glodon.paas.account.security.openid.service;

import org.openid4java.message.DirectError;
import org.openid4java.message.Message;
import org.openid4java.message.ParameterList;
import org.openid4java.server.ServerManager;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Don Li
 */
public class UserInteractionCallback extends HttpServlet {
    private ServerManager manager;

    @Override
    public void init() throws ServletException {
        ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        manager = (ServerManager) context.getBean("serverManager");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
    }

    private void processRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        ParameterList requestParams = new ParameterList(req.getParameterMap());
        String userSelectedId = req.getParameter("openid.identity");
        String userSelectedClaimedId = req.getParameter("openid.claimed_id");
        boolean authenticatedAndApproved = false;
        if ("true".equalsIgnoreCase(req.getParameter("approved"))) {
            authenticatedAndApproved = true;
        }

        Message responseMessage = manager.authResponse(requestParams, userSelectedId, userSelectedClaimedId, authenticatedAndApproved);
        if (responseMessage instanceof DirectError) {
            ServletOutputStream os = resp.getOutputStream();
            os.write(responseMessage.keyValueFormEncoding().getBytes());
            os.close();
            return;
        } else {
            resp.sendRedirect(responseMessage.getDestinationUrl(true));
        }
    }
}
